@echo off
rem Set UTF-8 encoding
chcp 65001 >nul

rem Get the directory where the script is located
set "PROJECT_ROOT=%~dp0"
set "PROJECT_ROOT=%PROJECT_ROOT:~0,-1%"

echo Project root directory: %PROJECT_ROOT%
echo.

rem Check if uv is installed
echo Checking uv installation...
uv --version >nul 2>&1
if %ERRORLEVEL% NEQ 0 (
    echo Error: uv is not installed or not in PATH!
    echo Please install uv first: https://docs.astral.sh/uv/getting-started/installation/
    pause
    exit /b 1
) else (
    echo uv is available
)

rem Create virtual environment and install dependencies (same as original)
echo.
echo Checking/Creating virtual environment...
if not exist "%PROJECT_ROOT%\.venv" (
    echo Creating virtual environment with Python 3.11...
    uv venv --python 3.11
    if %ERRORLEVEL% NEQ 0 (
        echo Error: Failed to create virtual environment!
        pause
        exit /b 1
    )
)

echo Installing/Syncing dependencies...
if exist "%PROJECT_ROOT%\pyproject.toml" (
    uv sync
) else if exist "%PROJECT_ROOT%\requirements.txt" (
    uv pip install -r requirements.txt
)

rem Create restart loop
set RESTART_COUNT=0
set MAX_RESTARTS=10

:RESTART_LOOP
if %RESTART_COUNT% GEQ %MAX_RESTARTS% (
    echo 达到最大重启次数 %MAX_RESTARTS%，停止重启
    pause
    exit /b 1
)

set /a RESTART_COUNT+=1
echo.
echo ========================================
echo 第 %RESTART_COUNT% 次启动服务器
echo ========================================
echo.

uv run python .\src\run_server.py

rem Check exit code
if %ERRORLEVEL% EQU 0 (
    echo 服务器正常退出
    goto END
) else (
    echo 服务器异常退出，退出码: %ERRORLEVEL%
    echo 等待5秒后重启...
    timeout /t 5 /nobreak >nul
    goto RESTART_LOOP
)

:END
echo 服务器管理器退出
pause